/**
 * 二维码下载打印
 */
import React from 'react';
import { Divider, message } from 'antd';
import QRCode from 'qrcode-react';
import html2canvas from 'html2canvas';
import logo from '@/assets/logo2.png';
import { primaryColor } from '@/defaultSettings';
import { useRequest } from '@/hooks';
import bg from './qrcode_bg.png';
import { getFirstOrgInfo } from '../../service';

import * as FileSaver from 'file-saver';
import 'canvas-toBlob';

const ImageDownload = ({ size = 240, ...rest }) => {
    const qrCodeRef = React.useRef(null);
    const canvasRef = React.useRef(null);
    const imageRef = React.useRef('');

    // 获取通知模板
    const { data: orgInfo } = useRequest(getFirstOrgInfo, {
        formatResult: res => {
            if (res) {
                const { code, data, msg } = res;
                if (code === 10000) {
                    if (data && data.length > 0) {
                        return {
                            orgName: data?.[0]?.organizationName,
                            orgNameEn: data?.[0]?.organizationNameEnglish
                        };
                    }
                    return undefined;
                }
                message.error(msg);
            }
            return undefined;
        }
    });

    const getCanvas = () =>
        new Promise((resolve, reject) => {
            if (canvasRef.current) {
                resolve();
                return;
            }
            const canvas = qrCodeRef.current?.refs?.canvas;
            if (!canvas) {
                reject();
                return;
            }
            const scaledCanvas = document.createElement('canvas');
            const context = scaledCanvas.getContext('2d');
            scaledCanvas.width = size;
            scaledCanvas.height = size;
            const image = new Image();
            image.onload = () => {
                context.drawImage(image, 0, 0, size, size);
                canvasRef.current = scaledCanvas;
                resolve();
            };
            image.onerror = () => {
                reject();
            };
            const src = canvas.toDataURL('image/png');
            imageRef.current = src;
            image.src = src;
        });

    const handlePrint = () => {
        const wind = window.open('', 'new', 'toolbar=no,scrollbars=yes,menubar=no');
        getCanvas()
            .then(() => {
                const printData = `
                <html>
                    <head>
                        <title></title>
                    </head>
                    <body>
                        <div style="border-radius: 4px; box-shadow: 0px 4px 16px 0px rgba(0, 0, 0, 0.12); overflow: hidden;width: ${size}px;">
                            <div
                                style="padding: 8px;display: flex;justify-content: center;align-items: center;font-size: 16px;color: ${primaryColor};"
                            >
                                <img src="${logo}" width="40" height="40 alt="" style="margin-right: 8px;flex-shrink: 0;"} />
                                <div style="word-break: break-all;">
                                    <div>${orgInfo?.orgName || '微微科技集团'}</div>
                                    ${orgInfo?.orgNameEn && `<div>${orgInfo?.orgNameEn || ''}</div>`}
                                </div>
                            </div>
                            <div style="position: relative; display: flex; justify-content: center; align-items: center;">
                                <img src="${bg}" width="${size}" height="${size}" alt="" />
                                <div
                                    style="position: absolute;display: inherit;background: #fff;padding: 5px;border-radius: 4px;"
                                >
                                    <img src="${imageRef.current}" width="${(size * 2) / 3}" alt="" />
                                </div>
                            </div>
                        </div>
                    </body>
                </html>`;
                wind.document.body.innerHTML = printData;
                // setTimeout优化多次点击时，有时无内容的问题
                setTimeout(() => {
                    wind.print();
                    wind.close();
                }, 10);
            })
            .catch(() => {
                message.error('调用打印功能出错');
            });
    };

    const getQrCodeUrl = () => `${window.location.origin}/external/interview/signIn`;

    // 下载二维码图片
    const downQrCode = () => {
        getCanvas()
            .then(() => {
                if (!canvasRef.current) {
                    return;
                }
                html2canvas(document.getElementById('qrcode-download')).then(can => {
                    can.toBlob(blob => {
                        FileSaver.saveAs(blob, '面试签到二维码.png');
                    });
                });
            })
            .catch(() => {
                message.error('下载二维码出错');
            });
    };

    const renderImage = (id, style) => (
        <div
            id={id}
            style={{
                borderRadius: 4,
                boxShadow: '0px 4px 16px 0px rgba(0, 0, 0, 0.12)',
                overflow: 'hidden',
                background: '#fff',
                padding: 0,
                ...style
            }}
        >
            <div
                style={{
                    display: 'flex',
                    justifyContent: 'center',
                    alignItems: 'center',
                    fontSize: 16,
                    color: primaryColor,
                    background: '#fff',
                    padding: 8
                }}
            >
                <img src={logo} width={40} height={40} alt="" style={{ marginRight: 8, flexShrink: 0 }} />
                <div style={{ wordBreak: 'break-all' }}>
                    <div>{orgInfo?.orgName || '微微科技集团'}</div>
                    {orgInfo?.orgNameEn && <div>{orgInfo?.orgNameEn || ''}</div>}
                </div>
            </div>
            <div style={{ position: 'relative', display: 'flex', justifyContent: 'center', alignItems: 'center' }}>
                <img src={bg} width={size} height={size} alt="" />
                <div
                    style={{
                        position: 'absolute',
                        display: 'inherit',
                        background: '#fff',
                        padding: 5,
                        borderRadius: 4
                    }}
                >
                    <QRCode
                        ref={qrCodeRef}
                        size={(size * 2) / 3}
                        value={getQrCodeUrl()}
                        // logo={logo}
                        // logoWidth={60}
                        // logoHeight={60}
                        {...rest}
                    />
                </div>
            </div>
        </div>
    );

    return (
        <div style={{ width: size }}>
            {renderImage()}
            <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', padding: '8px 0' }}>
                <a onClick={downQrCode}>下载</a>
                <Divider type="vertical" style={{ top: 1 }} />
                <a onClick={handlePrint}>打印</a>
            </div>
            {/* 二次渲染是为了解决html2canvas滚动后截屏会错位的问题，无奈之举 */}
            {renderImage('qrcode-download', { position: 'fixed', left: '10000%', top: 0 })}
        </div>
    );
};

export default ImageDownload;
